<?php
namespace App\Module\Teacher\Service;

use App\Constants\Constant;
use App\Exception\AppException;
use App\Model\Foot;
use App\Model\Resource;
use App\Module\Teacher\Request\Foot\CreateRequest;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Qbhy\HyperfAuth\AuthManager;

class FootService {

    /**
     * @Inject()
     * @var ChildService $childService
     */
    private $childService;

    /**
     * @Inject()
     * @var AuthManager $authManager'
     */
    private $authManager;

    public function search($is_teacher,$child_id,$start_time,$end_time,$pagesize){
        $query = Foot::query()->latest("foot_id")
            ->with("resources");

        if($is_teacher){
            $query->where("source",Constant::SOURCE_TEACHER)
                ->where("source_id",$this->authManager->guard(Constant::TEACHER)->user()->getId());
        }
        if(!empty($child_id)){
            $query->where("child_id",$child_id);
        }
        if(!empty($start_time)){
            $query->whereDate("add_time",">=" ,$start_time);
        }
        if(!empty($end_time)){
            $query->whereDate("add_time","<=" ,$end_time);
        }

        return $query->paginate($pagesize);
    }

    public function create(CreateRequest $request){
        return Db::transaction(function () use($request){
            $child = $this->childService->getById($request->input("child_id"));
            $foot = new Foot();
            $foot->fill($request->all());
            $foot->setAttribute("child_name",$child->getAttribute("name"));
            $foot->setAttribute("child_photo",$child->getAttribute("photo"));
            $foot->setAttribute("source",Constant::SOURCE_TEACHER);
            $foot->setAttribute("source_id",$this->authManager->guard(Constant::TEACHER)->user()->getId());
            $foot->setAttribute("source_name",$this->authManager->guard(Constant::TEACHER)->user()->name);
            $foot->save();

            if(!$request->has(["resources"])){
                return;
            }

            $resources = $request->input("resources");
            foreach ($resources as $v){
                $resource = new Resource();
                $resource->setAttribute("source_id",$foot->foot_id);
                $resource->setAttribute("uri",$v);
                $resource->setAttribute("origin",Constant::ORIGIN_FOOT);
                $resource->save();
            }
        });
    }

    public function delete($id){
        return Db::transaction(function () use ($id){
            $foot = Foot::query()->findOrFail($id);
            if($foot->source_id != $this->authManager->guard(Constant::TEACHER)->user()->getId()){
                throw new AppException("非原发布者,无法删除!");
            }
            if($foot->resource_type != 0) {
                Resource::query()->where([['source_id', $id], ['origin', Constant::ORIGIN_FOOT]])->delete();
            }
            $foot->delete();
        });
    }
}